package com.junbao.androidinterview.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.junbao.androidinterview.R;
import com.junbao.androidinterview.bean.RepoBean;
import com.junbao.androidinterview.net.interceptor.LoggerInterceptor;
import com.junbao.androidinterview.net.service.GitHubService;
import com.junbao.androidinterview.utils.LogUtils;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.List;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btnSend;
    private Subscription subscription;
    private Button btnSend2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit);

        initView();
    }

    private void initView() {
        btnSend = (Button) findViewById(R.id.btn_send);
        btnSend2 = (Button) findViewById(R.id.btn_send2);
        btnSend.setOnClickListener(this);
        btnSend2.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        // loadData();
        if (view == btnSend){
            testBackgroundPressure2();
        }else if (view == btnSend2){
            subscription.request(3);
        }
    }


    /**
     * 背压
     */
    public void testBackgroundPressure1() {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
                //死循环
                while (true) {
                    System.out.println("subscribe : Hello World");
                    e.onNext("Hello World");
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(Schedulers.newThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        sleep(10000);
                        System.out.println("accept Hello world");
                    }
                });
    }


    public void testBackgroundPressure2() {
        Flowable.create(new FlowableOnSubscribe<String>() {
            @Override
            public void subscribe(@NonNull FlowableEmitter<String> e) throws Exception {
                LogUtils.d("send:Hello World1");
                e.onNext("Hello World1");
                LogUtils.d("send:Hello World2");
                e.onNext("Hello World2");
                LogUtils.d("send:Hello World3");
                e.onNext("Hello World3");
            }
        }, BackpressureStrategy.ERROR)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.newThread())
                .subscribe(new Subscriber<String>() {


                    @Override
                    public void onSubscribe(Subscription s) {
                        subscription = s;
                        //像FLowable申请处理3条数据
                      //  s.request(3);
                        LogUtils.d("onSubscribe");
                    }

                    @Override
                    public void onNext(String s) {
                        LogUtils.d("onNext=" + s);
                    }

                    @Override
                    public void onError(Throwable t) {
                        LogUtils.d("onError=" + t.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        LogUtils.d("onComplete");
                    }
                });
    }

    public void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void loadData() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new LoggerInterceptor())
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();

        GitHubService gitHubService = retrofit.create(GitHubService.class);
        gitHubService.listRepos("octocat").enqueue(new Callback<List<RepoBean>>() {
            @Override
            public void onResponse(Call<List<RepoBean>> call, Response<List<RepoBean>> response) {
                List<RepoBean> body = response.body();
                LogUtils.d("success" + body.toString());
                btnSend.setText(body.toString());
            }

            @Override
            public void onFailure(Call<List<RepoBean>> call, Throwable t) {
                LogUtils.d("failure");
            }
        });

    }
}